85. Maximal Rectangle - LeetCode Solution


Dynamic Programming Stack

Python Code:

class Solution:
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        def MHA(heights):
            if len(heights) == 0:
                return 0

            stack = []

            left = []
            right = []

            for i in range(len(heights)):

                while len(stack) != 0 and heights[stack[-1]] >= heights[i]:
                    stack.pop()

                if len(stack) == 0:
                    left.append(0)
                else:
                    left.append(stack[-1] + 1)

                stack.append(i)

            stack = []

            for i in range(len(heights) - 1, -1, -1):
                while len(stack) != 0 and heights[stack[-1]] >= heights[i]:
                    stack.pop()

                if len(stack) == 0:
                    right.append(len(heights) - 1)
                else:
                    right.append(stack[-1] - 1)

                stack.append(i)

            right = right[::-1]


            ans = []

            for i in range(len(right)):
                ans.append((right[i] - left[i] + 1) * heights[i])

            return max(ans)
        
        
        if len(matrix) == 0:
            return 0
        area = []


        x = [0] * len(matrix[0])


        for i in range(len(matrix)):

            for j in range(len(matrix[i])):
                if int(matrix[i][j]) == 0:
                    x[j] = 0
                else:
                    x[j] += int(matrix[i][j])


            area.append(MHA(x))


        print(max(area))
        return max(area)


Comments

Submit
0 Comments
More Questions

1744A - Number Replacement
1744C - Traffic Light
1744B - Even-Odd Increments
637B - Chat Order
546C - Soldier and Cards
18D - Seller Bob
842B - Gleb And Pizza
1746D - Paths on the Tree
1651E - Sum of Matchings
19A - World Football Cup
630P - Area of a Star
1030C - Vasya and Golden Ticket
1529D - Kavi on Pairing Duty
1743A - Password
1743B - Permutation Value
1743C - Save the Magazines
1743D - Problem with Random Tests
1070K - Video Posts
767C - Garland
1201B - Zero Array
1584C - Two Arrays
1131C - Birthday
1285B - Just Eat It
1743F - Intersection and Union
771A - Bear and Friendship Condition
1208E - Let Them Slide
656A - Da Vinci Powers
1025A - Doggo Recoloring
257A - Sockets
231C - To Add or Not to Add